import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Button, Popconfirm, Tag, notification } from 'antd';
import type { RoleProps } from './src/data';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { delAuth } from '@/utils/utils';
import ProTable from '@ant-design/pro-table';
import { queryRole, delRole } from '@/services/role';
import { queryMenu, createMenu } from '@/services/menu';
import { useIntl, history } from 'umi';
import { authColor } from './constants';
import type { EditTreeType } from '@/components/EditTree/data';

type GithubIssueItem = {
  _id: string;
  name: string;
  registerTime: string;
};

const RoleManager: React.FC<RoleProps & History> = () => {
  const actionRef = useRef<ActionType>();
  const intl = useIntl();
  const [dataSource, setDataSource] = useState<GithubIssueItem[]>([]);
  const [menuData, setMenuData] = useState<EditTreeType[]>([]);

  useEffect(() => {
    const getData = async () => {
      const resMenu = await queryMenu();
      if (resMenu) {
        setMenuData(resMenu.data?.menuData);
      }
      const res = await queryRole();
      if (res) {
        setDataSource(res.data);
      }
    };
    getData();
  }, []);

  const onDelete = async (name: string) => {
    delAuth(menuData, name);
    await createMenu({ menuData });
    const res = await delRole({ name });
    if (res) {
      const resRole = await queryRole();
      if (resRole) {
        setDataSource(resRole.data);
      }
      notification.success({
        message: res.message,
      });
    }
  };

  const onEdit = async (name: string) => {
    history.push({
      pathname: '/manager/roleManager/create',
      query: { type: 'edit' },
      state: { name },
    });
  };

  const reduceMenuData = (data: EditTreeType[], authName: string, arrTemp: string[]) => {
    data.forEach((item: EditTreeType) => {
      if ((item.authority?.indexOf(authName) as number) > -1) {
        arrTemp.push(item.name as string);
      }
      if (item.children) {
        reduceMenuData(item.children, authName, arrTemp);
      }
    });
  };

  const renderAuth = (_: any, record: any) => {
    const authArr: string[] = [];
    reduceMenuData(menuData, record.name, authArr);
    console.log(authArr);
    // return <Tag color="red" key={authArr[0]} >{authArr[0]}</Tag>;
    return (
      <span>
        {authArr.map((item: string) => {
          return (
            <Tag color={authColor[item]?.color} key={item}>
              {intl.formatMessage({
                id: `menu.${item}`,
                defaultMessage: 'item',
              })}
            </Tag>
          );
        })}
      </span>
    );
  };

  const columns: ProColumns<GithubIssueItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      key: 'index',
      width: 48,
    },
    {
      title: '角色名',
      dataIndex: 'name',
      key: 'name',
      copyable: true,
      ellipsis: true,
      tip: '标题过长会自动收缩',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '权限',
      dataIndex: 'name',
      render: renderAuth,
    },
    {
      title: '创建时间',
      key: 'registerTime',
      dataIndex: 'registerTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <a
          key="editable"
          onClick={() => {
            onEdit(record.name);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="top"
          title="确定删除嘛？"
          onCancel={() => onDelete(record.name)}
          cancelButtonProps={{ type: 'primary', danger: true }}
          okText="取消"
          cancelText="是的"
          okType="default"
        >
          <Button key="view" type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer className="role_manager">
      <Card>
        <Button
          type="primary"
          onClick={() => {
            history.push('/manager/roleManager/create');
          }}
        >
          新建角色
        </Button>
        <ProTable<GithubIssueItem>
          dataSource={dataSource}
          columns={columns}
          actionRef={actionRef}
          // request={async () => {
          //   const res = await queryRole();
          //   if (res) {
          //     return res;
          //   }
          //   return null;
          // }}
          editable={{
            type: 'multiple',
          }}
          rowKey={(record) => record.name}
          search={{
            labelWidth: 'auto',
          }}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            pageSize: 5,
          }}
          dateFormatter="string"
          headerTitle="角色列表"
        />
      </Card>
    </PageContainer>
  );
};

export default RoleManager;
